package com.atguigu.gulimail.product.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.atguigu.common.to.*;
import com.atguigu.common.utils.R;
import com.atguigu.gulimail.product.dao.*;
import com.atguigu.gulimail.product.entity.*;
import com.atguigu.gulimail.product.feign.CouponService;
import com.atguigu.gulimail.product.feign.ESService;
import com.atguigu.gulimail.product.feign.WareService;
import com.atguigu.gulimail.product.service.*;
import com.atguigu.gulimail.product.vo.sku.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    ProductAttrValueDao productAttrValueDao;
    @Autowired
    SkuInfoDao skuInfoDao;
    @Autowired
    SkuImagesDao skuImagesDao;
    @Autowired
    SkuSaleAttrValueDao skuSaleAttrValueDao;
    @Autowired
    CouponService couponService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    BrandService brandService;
    @Autowired
    WareService wareService;
    @Autowired
    ProductAttrValueService attrValueService;
    @Autowired
    AttrService attrService;
    @Autowired
    ESService esService;
    @Autowired
    private SpuInfoDescDao spuInfoDescDao;
    @Autowired
    private SpuImagesDao spuImagesDao;
    @Autowired
    private AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryByCondition(Map<String, Object> params) {
        final IPage<SpuInfoEntity> page = new Query<SpuInfoEntity>().getPage(params);
        final QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        final String key = (String) params.get("key");
        if (!StringUtils.isBlank(key)) {
            wrapper.and(w -> w.eq("id", key).or().like("spu_name", key));
        }
        String brandIdStr = (String) params.get("brandId");
        if (!StringUtils.isBlank(brandIdStr)) {
            Long brandId = Long.parseLong(brandIdStr);
            if (brandId > 0) {
                wrapper.eq("brand_id", brandId);
            }
        }
        final String catelogIdStr = (String) params.get("catelogId");
        if (!StringUtils.isBlank(catelogIdStr)) {
            Long catelogId = Long.parseLong(catelogIdStr);
            if (catelogId > 0) {
                wrapper.eq("catalog_id", catelogId);
            }
        }
        final String statusStr = (String) params.get("status");
        if (!StringUtils.isBlank(statusStr)) {
            final Integer status = Integer.parseInt(statusStr);
            wrapper.eq("publish_status", status);
        }
        IPage<SpuInfoEntity> pageX = this.page(
                page, wrapper
        );
        return new PageUtils(pageX);
    }

    @Override
    public void spuUp(Long spuId) {
        //查询spu对应的所有sku.
        final List<SkuInfoEntity> skuInfoEntities =
                skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));


        final List<ProductAttrValueEntity> baseAttrs =
                attrValueService.queryAttrBySpuId(spuId);

        final List<Long> baseAttrIds =
                baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrIds(baseAttrIds);
        List<Attrs> attrsList = new ArrayList<>();
        if (searchAttrIds.size() > 0) {
            Set<Long> searchIdSets = new HashSet<>();
            searchIdSets.addAll(searchAttrIds);
            for (ProductAttrValueEntity attrValueEntity : baseAttrs) {
                if (searchIdSets.contains(attrValueEntity.getAttrId())) {
                    final Attrs attr = new Attrs();
                    BeanUtils.copyProperties(attrValueEntity, attr);
                    attrsList.add(attr);
                }
            }

        }
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        skuInfoEntities.forEach(skuInfoEntity -> {
            final Long skuId = skuInfoEntity.getSkuId();
            final SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());

            final R r = wareService.getStock(skuId);
            if (r.isOk()) {
                final Integer stockCount = (Integer) r.get("stockCount");
                if (stockCount > 0) {
                    skuEsModel.setHasStock(true);
                }
            }
            skuEsModel.setHotScore(0L);
            final Long brandId = skuInfoEntity.getBrandId();
            final BrandEntity brandEntity = brandService.getById(brandId);
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setAttrs(attrsList);
            skuEsModels.add(skuEsModel);
            System.out.println(skuEsModel);
        });
        esService.skusUp(skuEsModels);
    }

    private void saveSpuOtherInfo(SpuVo spuVo, Long spuId) {
        //2、保存Spu的描述图片 pms_spu_info_desc
        if (null != spuVo.getDecript() && spuVo.getDecript().size() > 0) {
            final String join = String.join(",", spuVo.getDecript());
            final SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
            spuInfoDescEntity.setSpuId(spuId);
            spuInfoDescEntity.setDecript(join);
            spuInfoDescDao.insert(spuInfoDescEntity);
        }
        //3、保存spu的图片集 pms_spu_images
        if (null != spuVo.getImages() && spuVo.getImages().size() > 0) {

            for (int i = 0; i < spuVo.getImages().size(); i++) {
                final String imgUrl = spuVo.getImages().get(i);
                if (StringUtils.isBlank(imgUrl)) {
                    continue;
                }
                final SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuId);
                spuImagesEntity.setImgUrl(imgUrl);
                spuImagesEntity.setImgSort(i + 1);
                spuImagesDao.insert(spuImagesEntity);
            }

        }
        //4、保存spu的规格参数;pms_product_attr_value
        final List<BaseAttrBean> baseAttrs = spuVo.getBaseAttrs();
        if (null != baseAttrs && baseAttrs.size() > 0) {
            for (int i = 0; i < baseAttrs.size(); i++) {
                BaseAttrBean baseAttr = baseAttrs.get(i);
                ProductAttrValueEntity spuAttrValueEntity = new ProductAttrValueEntity();
                spuAttrValueEntity.setAttrId(baseAttr.getAttrId());
                spuAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
                final AttrEntity attrEntity = attrDao.selectById(baseAttr.getAttrId());
                spuAttrValueEntity.setAttrName(attrEntity.getAttrName());
                spuAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
                spuAttrValueEntity.setSpuId(spuId);
                spuAttrValueEntity.setAttrSort(i + 1);
                productAttrValueDao.insert(spuAttrValueEntity);
            }
        }
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(spuVo.getBounds(), spuBoundsTo);
        spuBoundsTo.setSpuId(spuId);
        couponService.saveSpuBounds(spuBoundsTo);
    }

    private void saveSkuOtherInfo(SkuBean skuBean, Long spuId, Long skuId) {
        //5.2)、sku的图片信息;pms_sku_images
        final List<ImageBean> images = skuBean.getImages();
        if (null != images && images.size() > 0) {
            for (int i = 0; i < images.size(); i++) {
                ImageBean imageBean = images.get(i);
                final SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                BeanUtils.copyProperties(imageBean, skuImagesEntity);
                skuImagesEntity.setSkuId(skuId);
                skuImagesEntity.setImgSort(i + 1);
                skuImagesDao.insert(skuImagesEntity);
            }
        }
        //5.3)、sku的销售属性信息:pms_sku_sale_attr_value
        final List<AttrBean> saleAttrs = skuBean.getAttr();
        if (null != saleAttrs && saleAttrs.size() > 0) {
            for (int i = 0; i < saleAttrs.size(); i++) {
                AttrBean attrBean = saleAttrs.get(i);
                final SkuSaleAttrValueEntity skuSaleAttrValueEntity =
                        new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attrBean, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuId);
                skuSaleAttrValueEntity.setAttrSort(i + 1);
                skuSaleAttrValueDao.insert(skuSaleAttrValueEntity);
            }
        }
        //5.4)、sku的优惠、满减等信息;gulimall sms->sms_sku ladder|sms_sku_full_reduction\s
        if (skuBean.getFullCount() > 0
                && skuBean.getDiscount().compareTo(BigDecimal.ZERO) > 0
        ) {
            final SkuLadderTo skuLadderTo = new SkuLadderTo();
            BeanUtils.copyProperties(skuBean, skuLadderTo);
            skuLadderTo.setSkuId(skuId);
            couponService.saveSkuLadder(skuLadderTo);
        }
        if (skuBean.getFullPrice().compareTo(BigDecimal.ZERO) > 0 &&
                skuBean.getReducePrice().compareTo(BigDecimal.ZERO) > 0
        ) {
            final SkuFullReductionTo skuFullReductionTo = new SkuFullReductionTo();
            BeanUtils.copyProperties(skuBean, skuFullReductionTo);
            skuFullReductionTo.setSkuId(skuId);
            couponService.saveSkuFullReduction(skuFullReductionTo);
        }
        final List<MemberPriceBean> memberPrices = skuBean.getMemberPrice();
        if (null != memberPrices && memberPrices.size() > 0) {
            for (MemberPriceBean memberPriceBean : memberPrices) {
                final MemberPriceTo memberPriceTo = new MemberPriceTo();
                memberPriceTo.setSkuId(skuId);
                memberPriceTo.setMemberPrice(memberPriceBean.getPrice());
                memberPriceTo.setMemberLevelId(memberPriceBean.getId());
                memberPriceTo.setMemberLevelName(memberPriceBean.getName());
                memberPriceTo.setAddOther(1);
                couponService.saveMemberPrice(memberPriceTo);
            }
        }
    }


    @Override
    @Transactional
    public void save(SpuVo spuVo) {
        //1、保存spu基本信息 pms_spu_info
        final SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuVo, spuInfoEntity);
        spuInfoEntity.setCatalogId(spuVo.getCatelogId());
        this.save(spuInfoEntity);
        //remote call.
        final Long spuId = spuInfoEntity.getId();
        saveSpuOtherInfo(spuVo, spuId);

//5、保存spu的积分信息:gulimall_smssms_spu_bounds
//5、保存当前spu对应的所有sku信息;
        final List<SkuBean> skus = spuVo.getSkus();
        if (null != skus && skus.size() > 0) {
            for (SkuBean skuBean : skus) {
                //5.1)、sku的基本信息:pms_sku_info
                final SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(skuBean, skuInfoEntity);
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setCatalogId(spuVo.getCatelogId());
                skuInfoEntity.setBrandId(spuVo.getBrandId());
                final List<ImageBean> images = skuBean.getImages();
                if (null != images && images.size() > 0) {
                    final Optional<ImageBean> any =
                            images.stream().filter(imageBean -> imageBean.getDefaultImg() == 1).findAny();
                    any.ifPresent(imageBean -> skuInfoEntity.setSkuDefaultImg(imageBean.getImgUrl()));
                }
                skuInfoDao.insert(skuInfoEntity);
                final Long skuId = skuInfoEntity.getSkuId();
                this.saveSkuOtherInfo(skuBean, spuId, skuId);
            }
        }
    }

}